package com.plumejob.executor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.plumejob.executor.util.HttpsClient;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import java.util.List;

/**
 * 同步任务
 *
 * @author : pdl
 * @date : 2021/2/5 18:12
 */
public class SyncJobScheduler {

    private Scheduler scheduler;

    public void run(Scheduler scheduler) {
        this.scheduler = scheduler;
        List<PlumeJobDetail> remoteJobList = getRemoteJobList();
        if (remoteJobList == null || remoteJobList.isEmpty()) {
            return;
        }
        //TODO 状态细节要重新梳理
        // 不主动shutdown任务的scheduler

        remoteJobList.forEach(job -> {
            PlumeJobDetail runningJob = PlumeJobContext.getJobDetailByName(job.getJobName());
            //1。任务还在，如果字段属性未变（需要一个hashCode) 那么继续
            //2。值变了，那么关闭当前任务并移除当前任务，并启新任务
            if (runningJob != null) {
                try {
                    if (runningJob.hashCode() != job.hashCode()) {
                        PlumeJobContext.remove(job);
                        PlumeJobContext.runJob(job);
                    }
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            } else {
                //3。 任务不在启动新任务
                try {
                    PlumeJobContext.runJob(job);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public List<PlumeJobDetail> getRemoteJobList() {
        //TODO 异常细节
        String body = null;
        try {
            body = HttpsClient.get(PlumeJobContext.host + "/plumejob/queryJobListByAppName?appName=" + PlumeJobContext.appName);
        } catch (Exception e) {
            try {
                scheduler.shutdown();
            } catch (SchedulerException schedulerException) {
                schedulerException.printStackTrace();
            }
            e.printStackTrace();
        }
        if (body == null) {
            return null;
        }

        SyncResponse<PlumeJobDetail> response = JSON.parseObject(body, new TypeReference<SyncResponse<PlumeJobDetail>>() {
        });
        if (response.isOk()) {
            return response.getDatas();
        }
        return null;
    }
}
